class CommentsController < ApplicationController
  before_filter :find_article
  before_filter :login_required, :only => [ :destroy, :delete ]

  def create
    @comment = @article.comments.build(params[:comment])
    @comment.save!
    respond_to do |format|
      format.html { redirect_to article_url(@article) }
      format.xml  do
        headers["Location"] = article_url(@article)
        render(:nothing => true, :layout => false, :status => "201 Created")
      end
      # format.js
    end
  rescue
    respond_to do |format|
      format.xml  do
        render :action => 'new'
      end
    end
  end

  def destroy
    @article.comments.destroy(params[:id]) if request.delete?
    respond_to do |format|
      format.html do
        flash[:notice] = "Comment destroyed"
        redirect_to article_url(@article)
      end
      format.xml do
        headers["Location"] = article_url(@article)
        render :nothing => true, :layout => false, :status => '204 No Content'
      end
    end
  end

  def delete
    @comment = @article.comments.find(params[:id])
  end
  
  protected
    def find_article
      @article = Article.find(params[:article_id])
    end

    # only article author and admin can delete comments
    def authorized?
      current_user == @article.user || current_user.login == 'admin'
    end
end
